import React from 'react'

class TodoHead extends React.Component {
    state = {
        todo: ''
    }
    changeTodo = (e) => {
        this.setState({
            todo: e.target.value
        })
    }
    addItem = () => {
        // 调用父组件的addItem，并传递输入框的值
        this.props.addItem(this.state.todo)

        // 清空并自动获得焦点
        this.setState({
            todo: ''
        })

        this.input.focus();
    }
    render() {
        const { todo } = this.state;
        return (
            <div className="input-group mb-3">
                <input type="text" value={todo} onChange={this.changeTodo} className="form-control" id="input" ref={(el) => this.input = el} />
                <button className="btn btn-success" onClick={this.addItem}>添加</button>
            </div>
        )
    }
}

export default TodoHead;